from PySide6.QtWidgets import QDialog, QFileDialog, QMessageBox
from pyui.ptc_dialog_ui import Ui_PTCDialog
import sys
import os
import datetime
from workers.process_worker import ProcessWorker

class PTCDialog(QDialog, Ui_PTCDialog):
    def __init__(self, parent=None, log_widget=None):
        super().__init__(parent)
        self.setupUi(self)
        self.log_widget = log_widget
        self.inBrowse.clicked.connect(self.browse_input)
        self.outBrowse.clicked.connect(self.browse_output)
        self.startBtn.clicked.connect(self.run_ptc)
        self.worker = None
        self.prc_worker = None # 新增PRC分析工作线程

    def browse_input(self):
        directory = QFileDialog.getExistingDirectory(self, "选择输入目录")
        if directory:
            self.inEdit.setText(directory)

    def browse_output(self):
        directory = QFileDialog.getExistingDirectory(self, "选择输出目录")
        if directory:
            self.outEdit.setText(directory)

    def run_ptc(self):
        in_dir = self.inEdit.text().strip()
        out_dir = self.outEdit.text().strip()
        if not in_dir:
            QMessageBox.warning(self, "参数错误", "请选择输入目录！")
            return
        if not out_dir:
            out_dir = in_dir  # 如果未选择输出目录，默认用输入目录
        # 新建带时间戳的子文件夹
        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
        result_dir = os.path.join(out_dir, f'PTC_PRC_result_{timestamp}')
        try:
            os.makedirs(result_dir, exist_ok=True)
        except Exception as e:
            QMessageBox.critical(self, "文件夹创建失败", f"无法创建结果文件夹: {result_dir}\n错误: {e}")
            return
        self.append_log(f"开始进行PTC处理")
        cmd = ['python3', os.path.abspath("util/processPTC.py"), in_dir, result_dir]
        self.startBtn.setEnabled(False)
        self.worker = ProcessWorker(cmd)
        self.worker.output_signal.connect(self.append_log)
        self.worker.finished_signal.connect(lambda code: self.process_finished(code, result_dir))
        self.worker.start()
        self.accept()  # 立即关闭对话框

    def append_log(self, text):
        if self.log_widget:
            self.log_widget.append(text)
        else:
            QMessageBox.information(self, "运行结果", text)

    def process_finished(self, code, result_dir):
        self.startBtn.setEnabled(True)
        if code == 0:
            self.append_log(f"PTC处理完成，正在进行PRC分析...\n")
            # 自动调用plot_prc.py
            prc_cmd = ['python3', os.path.abspath("util/plot_prc.py"), result_dir]
            self.prc_worker = ProcessWorker(prc_cmd)
            self.prc_worker.output_signal.connect(self.append_log)
            self.prc_worker.finished_signal.connect(lambda code: self.prc_finished(code, result_dir))
            self.prc_worker.start()
        else:
            self.append_log("PTC处理失败或中断。")

    def prc_finished(self, code, result_dir):
        if code == 0:
            self.append_log("PRC分析完成！\n结果保存在: {}".format(result_dir))
        else:
            self.append_log("PRC分析失败或中断。") 